<?php

namespace Parser\Separator;

use Parser\Enquiry;
use Parser\parser;
use Parser\Repetition;

class CHINATP_AUTOPP implements BaseSeparator
{
    public static $ApiKindList = [
        3000 => '0301200', //车损
        4000 => '0301600', //三者
        5002 => '0301701', //司机
        5001 => '0301702', //乘客
    ];

    private $errorTip;


    public function interpreter(array $array, $parser)
    {

        if ($this->error($array, $parser)) {
            return;
        }

        $parser->result = $this->analysis($array);
    }

    /**
     *错误解析
     * Author:ls
     *
     * @param $array
     * @param $parser
     * @return bool
     */
    public function error(&$array, $parser): bool
    {
        if (isset($array['succ']) and !$array['succ']) {
            $parser->message = $errorMsg ?? $array['errMsg'] ?? '';
            $parser->code = '500';
            return true;
        }
//        //交强险重复投保
        if ($msgBZ = $array['data']['msgBZ'] ?? '') {
            if (preg_match('/重复投保/', $msgBZ)) {
                $parser->message = $msgBZ;
                $parser->code = '500';
                return true;
            }
        }
        //商业险重复投保
        if ($msgBS = $array['data']['msgBZ'] ?? '') {
            if (preg_match('/重复投保/', $msgBS)) {
                $this->errorTip = '商业险重复投保';
            }
        }
        if (!isset($array['data'])) {
            $parser->message = $msgBZ;
            $parser->code = '询价失败';
            return true;
        }
        $array = $array['data'];

        return false;
    }


    public function analysis($array): array
    {
        $enquiry = new Enquiry();

        $enquiry->setTaxTotal($array['pfCarShipTax']['sumPayTax'] ?? '0');
        $enquiry->setTaxPremium($array['pfCarShipTax']['taxDue'] ?? '0');

        $enquiry->setTCITotal($array['pfItemKindDto0801']['priceTaxTotal'] ?? '0');
        $enquiry->setTCIPremium($array['pfItemKindDto0801']['basePremium'] ?? '0');

        //系数相关
        if(!empty($array['pages'])) {
            foreach ($array['pages'] as $page) {
                if (preg_match("/商业险/", $page['pageName'])) {
                    $riskProfitDtos = array_column($page['pageRawData']['data']['riskProfitDtos'], null, 'profitCode');
                    //无赔款优待系数
                    $ncdRate = bcdiv($riskProfitDtos['N03']['adJustValue'] ?? '0', 100, 6);
                    $enquiry->setNCDRate($ncdRate);
                }
            }
        }
        if (isset($array['pfItemKindDto0802List'])) {
            foreach ($array['pfItemKindDto0802List'] as $kindList) {
                $code = (string)array_search($kindList['kindCode'], self::$ApiKindList);
                if (!$code) {
                    continue;
                }
                $coverages['code'] = (string)array_search($kindList['kindCode'], self::$ApiKindList);
                $coverages['shortName'] = $kindList['kindName'];
                $coverages['insuredDesc'] = (string)$kindList['sumInsured'] ?? '';
                $coverages['total'] = (string)$kindList['priceTaxTotal'];

                $enquiry->VCITotalAppend($kindList['priceTaxTotal']);
                $enquiry->VCIPremiumAppend($kindList['benchmarkPremium']);
                $enquiry->setVCIDiscount($kindList['discount']);

                $enquiry->setVCICoverages($coverages);
            }
        }
        //
        $enquiry->setTotal();
        if ($this->errorTip) {
            $enquiry->failure();
            $enquiry->setErrorTip($this->errorTip);
        }
        $enquiry->success();

        return $enquiry->get();
    }

    //数据解析
    public function repetition($array): Repetition
    {
        $repetition = new Repetition();


        if ($msgBS = $array['data']['msgBS'] ?? false) {

            if (mb_strlen($msgBS) < 400) {
                return $repetition;
            }
            //数据验证
            preg_match('/重复投保提示： ([\s\S]*)/', $msgBS, $matches);

            if (!$matches) {
                return $repetition;
            }
            $repeatMsg = explode("; ", trim($matches[1]));
            if (count($repeatMsg) < 10) {
                return $repetition;
            }
            $coverage = [];

            if (preg_match('/保单号：(\w+)/', $msgBS, $matches)) {
                $repetition->setLastPolicy($matches[1]);
            }
            foreach ($repeatMsg as &$value) {
                if (!$value) {
                    break;
                }
                $value = explode('：', $value);

                $column = trim($value[0]);

                $value = trim($value[1]);

                switch ($column) {
                    case '保险公司':
                        $repetition->setLastCompany($value);
                        break;
                    case '起保日期':
                        $repetition->setLastStartAt(date('Y-m-d H:i:s', strtotime($value)));
                        break;
                    case '终保日期':
                        $repetition->setLastEndTime(date('Y-m-d H:i:s', strtotime($value)));
                        break;
                    case '签单日期':
                        preg_match('/\w+/', $value, $value);
                        if ($value[0] ?? false) {
                            $repetition->setLastSignTime(date('Y-m-d H:i:s', strtotime($value[0])));
                        }
                        break;
                    case "号牌号码":
                        $repetition->setLicense($value);
                        break;
                    case "险种名称":
                        $coverage[] = $value;

                }
            }
            $repetition->setLastCoverage($coverage);

            if ($repetition->getLastCompany()) {
                $repetition->setStatus('success');
            }

        }
        return $repetition;
    }
}

